﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _07_02_解决sql注入
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //方案一
            //if (this.textBox1.Text.IndexOf("'") >= 0 || this.textBox2.Text.IndexOf("'") >= 0)
            //{
            //    MessageBox.Show("非法登录");
            //    return ;
            //}

            string connStr = "server=.;database=TestDB;uid=sa;pwd=200234.A";
            SqlConnection sqlcon = new SqlConnection(connStr);
            sqlcon.Open();
            //方案二 先查找数据库中得到用户名 根据数据库的的结果和文本框中的密码匹配
            //string sql = $"select * from Member where MemberAccount='" +
            //    $"{this.textBox1.Text}'";

            //方案三 使用参数化查询
            string sql = "select * from Member where MemberAccount=@Memberaccount and MemberPwd =@MemberPwd";

            SqlDataAdapter adp = new SqlDataAdapter(sql, sqlcon);
            adp.SelectCommand.Parameters.Add(new SqlParameter("@MemberAccount", this.textBox1.Text));
            adp.SelectCommand.Parameters.Add(new SqlParameter("@MemberPwd", this.textBox2.Text));
            DataTable dt = new DataTable();
            adp.Fill(dt);
            if (dt.Rows.Count == 0)
            {
                MessageBox.Show("用户名错误");
                return;
            }
            else
            {
                if (dt.Rows[0]["MemberPwd"].ToString().Equals(this.textBox2.Text))
                {
                    MessageBox.Show("登录成功");
                }
                else
                {
                    MessageBox.Show("密码错误");
                }
            }
            sqlcon.Close();
        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }
    }
}
